package com.bfl.lite.mvc.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LiteDispatcherServlet extends HttpServlet {

    private Properties config = new Properties();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.getWriter().write("Hello World!!!");





    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        // 读取配置contextConfLocation
        doConfig(servletConfig.getInitParameter("contextConfigLocation"));

        // 扫描带@LiteController注解的类
        doScanner(config.getProperty("basePackage"));



    }

    private void doScanner(String basePackage) {

        File baseDir = new File(basePackage.replace(".", "/"));
        File[] files = baseDir.listFiles();
        if (files == null || files.length == 0) {
            return;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                doScanner(basePackage + "." + file.getName());
            } else {

                System.out.println(file.getAbsolutePath());

            }
        }

    }

    private void doConfig(String contextConfigLocation) {

        if (contextConfigLocation.startsWith("classpath:")) {
            contextConfigLocation = contextConfigLocation.replace("classpath:", "");
        }

        InputStream is = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
            config.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
